package com.uziot.bucket.boot.message.convert;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;

/**
 * @author shidt
 * @version V1.0
 * @className FastJsonWebmvcConfiguration
 * @date 2021-07-22 11:34:37
 * @description FastJson消息转换器
 */

@ConditionalOnProperty(name = "message.converter.type", havingValue = Converter.FAST_JSON)
@Configuration
public class FastJsonWebmvcConfiguration implements WebMvcConfigurer {

    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverter() {
        //使用FastJson作为HTTP的序列换和反序列工具
        // 1.定义Converter转换器对象
        FastJsonHttpMessageConverter converter = new FastJsonMessageConverterAdapter();
        // 2.1设置转换器的配置信息
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(SerializerFeature.WriteNullStringAsEmpty);
        // 2.2设置编码,处理中文乱码
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        config.setCharset(StandardCharsets.UTF_8);
        // 3.将设置添加到转换器中
        converter.setFastJsonConfig(config);
        // 4.将转换器转为HttpMessageConverter并返回
        return new HttpMessageConverters(converter);
    }

}